<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :search="search"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.shop_statics_day_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="primary"
                   size="small"
                   plain
                   icon="el-icon-upload"
                   @click="handleImport">导 入
        </el-button>
        <el-button type="warning"
                   size="small"
                   plain
                   icon="el-icon-download"
                   @click="handleExport">导 出
        </el-button>
        <el-button type="primary"
                   size="small"
                   plain
                   @click="handleOpenDialog">数据对比
        </el-button>
      </template>
      <template slot-scope="{type,disabled}" slot="shopIdForm">
        <div>
          <el-autocomplete v-model="formShopName" style="width: 100%" :fetch-suggestions="queryShopAsync"
                           placeholder="搜索店铺名称" @select="handleFormShopSelect"></el-autocomplete>
        </div>
      </template>
      <template slot="search" slot-scope="{row,size}">
        <div class="el-form-item el-form-item--small avue-form__item--">
          <label class="el-form-item__label">店铺名称：</label>
          <el-input placeholder="请输入店铺名称" clearable :size="size" style="width:200px" v-model="search.shopName"></el-input>
        </div>
        <div class="el-form-item el-form-item--small avue-form__item--">
          <label class="el-form-item__label">下单时间：</label>
          <el-date-picker
            style="margin-right: 10px; width: 450px !important; height: 32px; line-height: 32px;"
            v-model="search.dateRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions">
          </el-date-picker>
        </div>
        <div class="el-form-item el-form-item--small avue-form__item--">
          <label class="el-form-item__label">所属客户：</label>
          <el-autocomplete v-model="tenantName" style="width:200px" :fetch-suggestions="queryTenantAsync"
                           placeholder="搜索所属客户" @select="handleTenantSelect" clearable @change="handleTenantChange"></el-autocomplete>
        </div>
      </template>
    </avue-crud>
    <el-dialog
      title="数据对比"
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="handleClose">
      <div class="header">
        <el-row :span="24">
          <el-col :span="24">
            <div class="el-form-item el-form-item--small avue-form__item--">
              <avue-checkbox all v-model="formCompare" placeholder="请选择内容" :dic="fieldDict" @change="handleGeneralCompare"></avue-checkbox>
            </div>
          </el-col>

          <el-col :span="24">
            <div class="el-form-item el-form-item--small avue-form__item--">
              <el-tag
                style="margin-right: 10px"
                v-for="(tag, index) in formShopTags"
                :key="tag.value"
                closable
                @close="handleRemoveTag(index)"
                type="text">
                {{tag.value}}
              </el-tag>
              <el-autocomplete v-model="shopName" style="width:200px" :fetch-suggestions="queryShopAsync"
                               placeholder="搜索店铺以添加对比店铺" @select="handleShopSelect" clearable></el-autocomplete>
            </div>
          </el-col>

          <el-col :span="24">
            <div class="el-form-item el-form-item--small avue-form__item--">
              <el-date-picker
                style="margin-right: 10px; width: 450px !important; height: 32px; line-height: 32px;"
                v-model="formDateRange"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
          </el-col>

          <el-col :span="24">
            <div class="el-form-item el-form-item--small avue-form__item--">
              <el-button type="primary" size="small" @click="handleGeneralCompare">生成对比图</el-button>
            </div>
          </el-col>
        </el-row>
      </div>

      <div class="content" v-if="compareVisible">
        <el-col :span="8" v-for="item in formCompare">
          <ShopStaticsMetric :data-list="compareDataList" :shops="formShopTags" :date-range="formDateRange" :metric="item" :dic="fieldDict" />
        </el-col>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false;">关 闭</el-button>
  </span>
    </el-dialog>
    <el-dialog title="数据导入"
               append-to-body
               :visible.sync="excelBox"
               width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate()">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, getListForCompare} from "@/api/shop/shop_statics_day";
import {mapGetters} from "vuex";
import {getToken} from "@/util/auth";
import {shopSelect} from "@/api/shop/shop";
import {setStore} from "@/util/store";
import {dateFormat} from "@/util/date";
import ShopStaticsMetric from "@/components/echart/shopStaticsMetric";
import {getSelect as tenantSelect} from "@/api/system/tenant";

export default {
  components: {
    ShopStaticsMetric
  },
  data() {
    return {
      compareVisible: true,
      compareDataList: [],
      formShopTags: [],
      formCompare: ['goodsCount', 'userVisitCount', 'viewCount', 'display', 'payUserCount', 'payTicketCount', 'amount'],
      formDateRange: '',
      fieldDict: [
        {
          label: '商品数',
          value: 'goodsCount'
        },
        {
          label: '访客数',
          value: 'userVisitCount'
        },
        {
          label: '浏览量',
          value: 'viewCount'
        },
        {
          label: '展现',
          value: 'display'
        },
        {
          label: '支付买家数',
          value: 'payUserCount'
        },
        {
          label: '支付订单数',
          value: 'payTicketCount'
        },
        {
          label: '金额',
          value: 'amount'
        },
      ],
      dialogVisible: false,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      search: {
        dateRange: '',
        shopName: '',
      },
      option: {
        height: 'auto',
        calcHeight: 210,
        labelWidth: 200,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        refreshBtn: false,
        column: [
          {
            label: "店铺",
            prop: "shopId",
            slot: true,
            formslot: true,
            editDisabled: true,
            rules: [{
              required: true,
              message: "请输入店铺id",
              trigger: "blur"
            }],
            search: false,
            type: 'select',
            dicUrl: "/api/celery-shop/shop/shop_select",
            props: {
              label: "label",
              value: "value"
            },
          },
          {
            label: "日期",
            prop: "date",
            editDisabled: true,
            rules: [{
              required: true,
              message: "请输入日期",
              trigger: "blur"
            }],
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd"
          },
          {
            label: "商品数",
            prop: "goodsCount",
            type: 'number',
            rules: [{
              required: true,
              message: "请输入商品数",
              trigger: "blur"
            }]
          },
          {
            label: "访客数",
            prop: "userVisitCount",
            type: 'number',
            rules: [{
              required: true,
              message: "请输入访客数",
              trigger: "blur"
            }]
          },
          {
            label: "浏览量",
            prop: "viewCount",
            type: 'number',
            rules: [{
              required: true,
              message: "请输入浏览量",
              trigger: "blur"
            }]
          },
          {
            label: "展现",
            prop: "display",
            type: 'number',
            rules: [{
              required: true,
              message: "请输入展现",
              trigger: "blur"
            }]
          },
          {
            label: "支付买家数",
            prop: "payUserCount",
            type: 'number',
            rules: [{
              required: true,
              message: "请输入支付买家数",
              trigger: "blur"
            }]
          },
          {
            label: "支付订单数",
            prop: "payTicketCount",
            type: 'number',
            rules: [{
              required: true,
              message: "请输入支付订单数",
              trigger: "blur"
            }]
          },
          {
            label: "金额",
            prop: "amount",
            type: 'number',
            rules: [{
              required: true,
              message: "请输入金额",
              trigger: "blur"
            }]
          },
          {
            label: "操作记录",
            overHidden: true,
            prop: "operateRecord",
            type: 'textarea',
            span: 24
          },
          {
            label: "操作建议",
            overHidden: true,
            prop: "operateSuggestion",
            type: 'textarea',
            span: 24
          },
        ]
      },
      data: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setHours(0, 0, 0, 0)
              end.setHours(23, 59, 59, 999)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setHours(0, 0, 0, 0)
              end.setHours(23, 59, 59, 999)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setHours(0, 0, 0, 0)
              end.setHours(23, 59, 59, 999)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setHours(0, 0, 0, 0)
              end.setHours(23, 59, 59, 999)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
              picker.$emit('pick', [start, end]);
            }
          }]
      },
      shopList: [],
      shopName: '',
      formShopName: '',
      tenantName: '',
      tenantList: [],
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/celery-shop-statics-day/shop-statics-day/import-data"
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          }
        ]
      },
    };
  },
  computed: {
    ...mapGetters(["permission", "shopStaticsSearch"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.shop_statics_day_add, false),
        viewBtn: this.vaildData(this.permission.shop_statics_day_view, false),
        delBtn: this.vaildData(this.permission.shop_statics_day_delete, false),
        editBtn: this.vaildData(this.permission.shop_statics_day_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
    this.LoadShopList()
    this.loadTenantList()
  },
  methods: {
    handleTenantSelect(val) {
      this.search.tenantId = val.id
    },
    handleTenantChange(val) {
      if (val === '') {
        this.search.tenantId = ''
      }
    },
    queryTenantAsync(queryString, cb) {
      const restaurants = this.tenantList;
      const results = queryString ? restaurants.filter(this.createTenantStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    },
    createTenantStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    loadTenantList() {
      tenantSelect().then(res => {
        this.tenantList = res.data.data.map(item => {
          return {value: item.tenantName, id: item.tenantId}
        })
      })
    },
    handleCompareRefresh() {
      this.compareVisible = false
      this.compareVisible = true
    },
    handleGeneralCompare() {
      const params = {}
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      params.startTime = dateFormat(start, 'yyyy-MM-dd 00:00:00')
      params.endTime = dateFormat(new Date(), 'yyyy-MM-dd 23:59:59')
      if (this.formDateRange !== '') {
        params.startTime = `${this.formDateRange[0]} 00:00:00`
        params.endTime = `${this.formDateRange[1]} 23:59:59`
      }
      if (this.formShopTags.length === 0) {
        this.$message.warning('请至少选择一个店铺!')
        return
      }
      params.shopIds = this.formShopTags.map(item => item.id).join(',')
      this.compareVisible = false
      getListForCompare(params).then(res => {
        this.compareDataList = res.data.data
        this.compareVisible = true
      })
    },
    handleRemoveTag(index) {
      this.formShopTags.splice(index, 1)
    },
    handleOpenDialog() {
      this.dialogVisible = true
    },
    handleShopSelect(val) {
      const ids = this.formShopTags.map(item => item.id)
      if (!ids.includes(val.id)) {
        this.formShopTags.push(val)
      }
      this.shopName = ''
    },
    handleFormShopSelect(val) {
      this.$set(this.form, 'shopId', val.id)
      this.$forceUpdate()
      // this.form.shopId = val.id
    },
    queryShopAsync(queryString, cb) {
      const restaurants = this.shopList;
      const results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    LoadShopList() {
      shopSelect().then(res => {
        this.shopList = res.data.data.map(item => {
          return {value: item.label, id: item.value}
        })
      })
    },
    handleImport() {
      this.excelBox = true
    },
    handleTemplate() {
      window.open(`/api/celery-shop-statics-day/shop-statics-day/export-template?blade-auth=${getToken()}`);
    },
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      done();
      this.excelBox = false;
      this.refreshChange();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    handleExport() {
      this.$confirm("是否导出店铺数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let exportUrl = `/api/celery-shop-statics-day/shop-statics-day/export-shop-statics-day?blade-auth=${getToken()}`
        if (this.search.dateRange && this.search.dateRange !== '') {
          exportUrl += `&date_datege=${this.search.dateRange[0]}&date_datele=${this.search.dateRange[1]}`
        }
        if (this.search.shopId) {
          exportUrl += `&shopId_equal=${this.search.shopId}`
        }
        window.open(exportUrl);
      });
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.search.dateRange = ''
      this.search.shopName = ''
      this.search.tenantId = ''
      this.tenantName = ''
      setStore({name: 'shop_statics_days_search', content: this.search})
      this.$forceUpdate()
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      setStore({name: 'shop_statics_days_search', content: this.search})
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (!this.search.dateRange || this.search.dateRange === '') {
        this.search = this.shopStaticsSearch
      }
      if (!this.search.shopName || this.search.shopName === '') {
        this.search = this.shopStaticsSearch
      }
      if (this.search.dateRange && this.search.dateRange !== '') {
        params.dateStart = this.search.dateRange[0]
        params.dateEnd = this.search.dateRange[1]
      }
      if (this.search.shopName && this.search.shopName !== '') {
        params.shopName = this.search.shopName
      }
      if (this.search.tenantId && this.search.tenantId !== '') {
        params.tenantId = this.search.tenantId
      }
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
.el-input__icon el-range__icon el-icon-date {
  vertical-align: middle;
  line-height: 32px;
}
.el-input__icon {
  height: auto;
}
.content {
  min-height: 1600px;
  background-color: #0f1325;
}
.avue-crud .el-input__inner, .avue-form .el-input__inner {
  height: 32px;
}
</style>
